<template>
  <view class="topic-list-page">
    <!-- 顶部导航栏 -->
    <view class="navbar">
      <view class="search-box" @click="gotoSearch">
        <uni-icons type="search" size="18" class="search-icon"></uni-icons>
        <text class="search-placeholder">搜索话题或内容...</text>
      </view>
      <view class="publish-btn" @click="gotoPublishTopic">
        <u-icon name="plus" size="20"></u-icon>
      </view>
    </view>

    <!-- 话题分类标签 -->
    <view class="topic-tabs">
      <scroll-view scroll-x class="tabs-scroll">
        <view class="tab-item" 
              v-for="(tab, index) in topicTabs" 
              :key="index"
              :class="{ active: currentTab === index }"
              @click="switchTab(index)">
          <text>{{ tab.name }}</text>
          <view class="tab-indicator" v-if="currentTab === index"></view>
        </view>
      </scroll-view>
    </view>

    <!-- 话题列表 -->
    <scroll-view scroll-y class="topic-scroll" @scrolltolower="loadMoreTopics">
      <view class="topic-list">
        <view class="topic-item" 
              v-for="(topic, index) in filteredTopics" 
              :key="topic.id"
              @click="gotoTopicDetail(topic.id)">
          <!-- 话题作者信息 -->
          <view class="topic-author">
            <image :src="topic.author.avatar" alt="用户头像" class="author-avatar"></image>
            <view class="author-info">
              <view class="author-name">
                <text>{{ topic.author.name }}</text>
                <view class="verified-badge" v-if="topic.author.verified">
                  <uni-icons type="checkmark-circle" size="14" color="#165DFF"></uni-icons>
                </view>
              </view>
              <view class="topic-time">
                <text>{{ topic.publishTime }}</text>
                <text class="topic-category" v-if="topic.category">· {{ topic.category }}</text>
              </view>
            </view>
          </view>
          
          <!-- 话题内容 -->
          <view class="topic-content">
            <view class="topic-title" v-if="topic.title">
              <text>{{ topic.title }}</text>
            </view>
            <view class="topic-text">
              <text>{{ topic.content }}</text>
            </view>
            
            <!-- 话题图片 -->
            <view class="topic-images" v-if="topic.images.length > 0">
              <view class="image-grid" :class="'grid-' + getImageGridClass(topic.images.length)">
                <image 
                  :src="imgUrl" 
                  alt="话题图片" 
                  class="topic-image"
                  v-for="(imgUrl, imgIndex) in topic.images" 
                  :key="imgIndex"
                ></image>
                <view class="image-count" v-if="topic.images.length > 9">
                  <text>+{{ topic.images.length - 9 }}</text>
                </view>
              </view>
            </view>
            
            <!-- 话题标签 -->
            <view class="topic-tags" v-if="topic.tags.length > 0">
              <view class="tag-item" v-for="(tag, tagIndex) in topic.tags" :key="tagIndex">
                #{{ tag }}
              </view>
            </view>
          </view>
          
          <!-- 话题互动数据 -->
          <view class="topic-actions">
            <view class="action-item" @click.stop="handleLike(topic, index)">
              <uni-icons 
                type="heart" 
                size="18" 
                :color="topic.isLiked ? '#FF4D4F' : '#86909C'" 
                :filled="topic.isLiked"
              ></uni-icons>
              <text class="action-count" :class="topic.isLiked ? 'liked' : ''">{{ topic.likeCount }}</text>
            </view>
            <view class="action-item" @click.stop="gotoTopicDetail(topic.id)">
              <uni-icons type="chatbubble" size="18" color="#86909C"></uni-icons>
              <text class="action-count">{{ topic.commentCount }}</text>
            </view>
            <view class="action-item" @click.stop="handleShare(topic)">
              <uni-icons type="share" size="18" color="#86909C"></uni-icons>
              <text class="action-count">{{ topic.shareCount }}</text>
            </view>
            <view class="action-item" @click.stop="handleCollect(topic, index)">
              <uni-icons 
                type="star" 
                size="18" 
                :color="topic.isCollected ? '#FFD700' : '#86909C'" 
                :filled="topic.isCollected"
              ></uni-icons>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view class="loading-more" v-if="isLoading">
        <uni-loading-icon size="24" color="#165DFF"></uni-loading-icon>
        <text class="loading-text">加载中...</text>
      </view>
      
      <!-- 没有更多数据 -->
      <view class="no-more" v-if="!hasMoreData && !isLoading && filteredTopics.length > 0">
        <text>没有更多内容了</text>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="filteredTopics.length === 0 && !isLoading">
        <uni-icons type="list" size="60" color="#C9CDD4"></uni-icons>
        <text class="empty-text">暂无相关话题</text>
        <button class="empty-btn" @click="gotoPublishTopic">发布第一个话题</button>
      </view>
    </scroll-view>

    <!-- 底部导航 -->
    <view class="tab-bar">
      <view class="tab-bar-item" v-for="(item, index) in tabBarItems" :key="index" @click="switchTabBar(index)">
        <uni-icons 
          :type="item.icon" 
          :size="22" 
          :color="currentTabBar === index ? '#165DFF' : '#86909C'"
          :filled="currentTabBar === index && item.filledOnActive"
        ></uni-icons>
        <text class="tab-bar-text" :class="currentTabBar === index ? 'active' : ''">{{ item.text }}</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 话题分类标签
      topicTabs: [
        { name: '全部', type: 'all' },
        { name: '技术讨论', type: 'technology' },
        { name: '设备评测', type: 'equipment' },
        { name: '飞行技巧', type: 'skills' },
        { name: '作品展示', type: 'works' },
        { name: '行业资讯', type: 'news' },
        { name: '活动组织', type: 'activities' }
      ],
      currentTab: 0, // 当前选中的标签
      
      // 话题列表数据
      topics: [],
      filteredTopics: [], // 过滤后的话题
      page: 1,
      pageSize: 10,
      hasMoreData: true,
      isLoading: false,
      
      // 底部导航
      tabBarItems: [
        { icon: 'home', text: '首页', filledOnActive: false },
        { icon: 'compose', text: '话题', filledOnActive: true },
        { icon: 'user', text: '我的', filledOnActive: false }
      ],
      currentTabBar: 1 // 当前选中的底部导航
    };
  },
  
  onLoad() {
    // 初始化加载话题数据
    this.loadTopics();
  },
  
  methods: {
    // 切换分类标签
    switchTab(index) {
      if (this.currentTab === index) return;
      this.currentTab = index;
      this.page = 1;
      this.topics = [];
      this.filteredTopics = [];
      this.hasMoreData = true;
      this.loadTopics();
    },
    
    // 加载话题数据
    loadTopics() {
      if (!this.hasMoreData || this.isLoading) return;
      
      this.isLoading = true;
      
      // 模拟API请求
      setTimeout(() => {
        const newTopics = this.generateMockTopics();
        this.topics = [...this.topics, ...newTopics];
        this.filterTopics();
        
        // 控制是否还有更多数据
        if (newTopics.length < this.pageSize) {
          this.hasMoreData = false;
        }
        
        this.page++;
        this.isLoading = false;
      }, 1500);
    },
    
    // 过滤话题（根据当前选中的标签）
    filterTopics() {
      const currentType = this.topicTabs[this.currentTab].type;
      if (currentType === 'all') {
        this.filteredTopics = this.topics;
      } else {
        this.filteredTopics = this.topics.filter(topic => topic.type === currentType);
      }
    },
    
    // 加载更多话题
    loadMoreTopics() {
      this.loadTopics();
    },
    
    // 处理点赞
    handleLike(topic, index) {
      const topicIndex = this.topics.findIndex(item => item.id === topic.id);
      if (topicIndex === -1) return;
      
      // 更新点赞状态和数量
      this.topics[topicIndex].isLiked = !this.topics[topicIndex].isLiked;
      this.topics[topicIndex].likeCount += this.topics[topicIndex].isLiked ? 1 : -1;
      
      // 同步更新过滤后的列表
      this.filterTopics();
      
      // 显示点赞反馈
      uni.showToast({
        title: topic.isLiked ? '点赞成功' : '取消点赞',
        icon: 'none',
        duration: 1500
      });
    },
    
    // 处理收藏
    handleCollect(topic, index) {
      const topicIndex = this.topics.findIndex(item => item.id === topic.id);
      if (topicIndex === -1) return;
      
      // 更新收藏状态
      this.topics[topicIndex].isCollected = !this.topics[topicIndex].isCollected;
      
      // 同步更新过滤后的列表
      this.filterTopics();
      
      // 显示收藏反馈
      uni.showToast({
        title: topic.isCollected ? '收藏成功' : '取消收藏',
        icon: 'none',
        duration: 1500
      });
    },
    
    // 处理分享
    handleShare(topic) {
      uni.share({
        title: topic.title || '来自无人机社区的分享',
        content: topic.content.substring(0, 50) + '...',
        success: () => {
          // 更新分享数量
          const topicIndex = this.topics.findIndex(item => item.id === topic.id);
          if (topicIndex !== -1) {
            this.topics[topicIndex].shareCount++;
            this.filterTopics();
          }
          
          uni.showToast({
            title: '分享成功',
            icon: 'none'
          });
        }
      });
    },
    
    // 获取图片网格样式
    getImageGridClass(count) {
      if (count === 1) return '1';
      if (count === 2 || count === 4) return '2';
      return '3';
    },
    
    // 生成模拟话题数据
    generateMockTopics() {
      const types = ['technology', 'equipment', 'skills', 'works', 'news', 'activities'];
      const categories = ['技术讨论', '设备评测', '飞行技巧', '作品展示', '行业资讯', '活动组织'];
      const tags = [
        ['大疆', 'Mavic 3', '航拍'],
        ['Phantom 4', '测绘', '行业应用'],
        ['飞行安全', '禁飞区', '法规'],
        ['后期制作', '剪辑', '素材'],
        ['农业植保', '无人机应用', '效率'],
        ['穿越机', 'FPV', '竞速']
      ];
      
      const mockTopics = [];
      
      for (let i = 0; i < this.pageSize; i++) {
        const id = (this.page - 1) * this.pageSize + i + 1;
        const typeIndex = Math.floor(Math.random() * types.length);
        const randomTags = tags[typeIndex];
        const imageCount = Math.floor(Math.random() * 10);
        
        // 生成随机图片数组
        const images = [];
        for (let j = 0; j < imageCount; j++) {
          const imgId = 1030 + j + Math.floor(Math.random() * 50);
          images.push(`https://picsum.photos/id/${imgId}/300/300`);
        }
        
        // 随机内容
        const contents = [
          '刚入手的大疆Mavic 3 Pro，试飞了几次感觉画质确实不错，特别是夜景模式提升明显。不过续航好像没有官方宣传的那么久，大家的使用情况怎么样？',
          '分享一下我的航拍作品，这是上周在海边拍摄的日出，用的是Phantom 4 RTK，后期稍微调色处理了一下。欢迎大家点评指导！',
          '关于无人机法规更新，最近了解到很多地区都加强了对无人机飞行的管控，特别是人口密集区域。有没有人知道最新的政策解读？',
          '请教一个问题，我的无人机最近总是出现GPS信号弱的情况，换了地方也一样，是什么原因导致的？该怎么解决呢？',
          '参加了上周末的无人机行业展会，看到了很多新设备和技术，特别是农业无人机的智能化程度越来越高了，未来应用前景广阔。',
          '第一次尝试穿越机飞行，差点炸机了，FPV飞行确实需要更多练习。有没有适合新手的穿越机推荐？',
          '分享我的飞行技巧：在大风天气下如何保持稳定拍摄？关键是要降低飞行高度，同时调整云台角度，大家可以试试。',
          '对比了几款主流的无人机电池，发现第三方品牌的性价比更高，但安全性让人担心。大家更倾向于原厂还是第三方电池？'
        ];
        
        const titles = [
          '大疆Mavic 3 Pro使用体验分享',
          '海边日出航拍作品',
          '最新无人机法规解读',
          'GPS信号弱问题求解',
          '无人机行业展会见闻',
          '穿越机新手入门指南',
          '大风天气飞行技巧',
          '无人机电池选购建议'
        ];
        
        const randomContentIndex = Math.floor(Math.random() * contents.length);
        
        mockTopics.push({
          id: id,
          type: types[typeIndex],
          category: categories[typeIndex],
          title: Math.random() > 0.3 ? titles[randomContentIndex] : '',
          content: contents[randomContentIndex],
          images: images,
          tags: randomTags.slice(0, Math.floor(Math.random() * randomTags.length) + 1),
          publishTime: this.getRandomTime(),
          likeCount: Math.floor(Math.random() * 200),
          commentCount: Math.floor(Math.random() * 50),
          shareCount: Math.floor(Math.random() * 30),
          isLiked: false,
          isCollected: false,
          author: {
            id: 1000 + Math.floor(Math.random() * 100),
            name: '用户' + Math.floor(Math.random() * 10000),
            avatar: `https://picsum.photos/id/${200 + Math.floor(Math.random() * 50)}/100/100`,
            verified: Math.random() > 0.7
          }
        });
      }
      
      return mockTopics;
    },
    
    // 生成随机时间
    getRandomTime() {
      const now = new Date();
      const randomHours = Math.floor(Math.random() * 72); // 3天内的随机时间
      const randomTime = new Date(now.getTime() - randomHours * 60 * 60 * 1000);
      
      const hours = randomTime.getHours();
      const minutes = randomTime.getMinutes();
      
      // 今天
      if (randomTime.toDateString() === now.toDateString()) {
        return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
      }
      
      // 昨天
      const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);
      if (randomTime.toDateString() === yesterday.toDateString()) {
        return `昨天 ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
      }
      
      // 更早
      const month = randomTime.getMonth() + 1;
      const day = randomTime.getDate();
      return `${month}月${day}日`;
    },
    
    // 跳转到话题详情
    gotoTopicDetail(topicId) {
      uni.navigateTo({
        url: `/pages/topic/topic-detail?id=${topicId}`
      });
    },
    
    // 跳转到发布话题
    gotoPublishTopic() {
      uni.navigateTo({
        url: '/pages/topic/publish-topic'
      });
    },
    
    // 跳转到搜索页面
    gotoSearch() {
      uni.navigateTo({
        url: '/pages/community/search'
      });
    },
    
    // 切换底部导航
    switchTabBar(index) {
      if (this.currentTabBar === index) return;
      this.currentTabBar = index;
      
      // 实际项目中根据不同的导航项跳转到不同页面
      switch(index) {
        case 0:
          uni.switchTab({
            url: '/pages/index/index'
          });
          break;
        case 1:
          // 当前页面
          break;
        case 2:
          uni.switchTab({
            url: '/pages/my/my'
          });
          break;
      }
    }
  }
};
</script>

<style scoped lang="scss">
// 颜色变量
$primary: #165DFF;
$primary-light: #E8F3FF;
$danger: #FF4D4F;
$warning: #FF7D00;
$success: #00B42A;
$text-primary: #1D2129;
$text-secondary: #4E5969;
$text-tertiary: #86909C;
$bg-light: #F5F7FA;
$bg-white: #FFFFFF;
$border-light: #E5E6EB;
$shadow-light: 0 2px 10px rgba(0, 0, 0, 0.05);

.topic-list-page {
  background-color: $bg-light;
  min-height: 100vh;
  padding-top: var(--status-bar-height);
  padding-bottom: 56px; // 为底部导航留出空间
}

// 导航栏
.navbar {
  display: flex;
  align-items: center;
  height: 50px;
  padding: 0 16px;
  background-color: $bg-white;
  border-bottom: 1px solid $border-light;
  
  .search-box {
    flex: 1;
    height: 36px;
    background-color: $bg-light;
    border-radius: 18px;
    display: flex;
    align-items: center;
    padding: 0 16px;
    
    .search-icon {
      color: $text-tertiary;
      margin-right: 8px;
    }
    
    .search-placeholder {
      font-size: 14px;
      color: $text-tertiary;
      flex: 1;
    }
  }
  
  .publish-btn {
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 10px;
    color: $primary;
    background-color: $primary-light;
    border-radius: 50%;
  }
}

// 话题分类标签
.topic-tabs {
  background-color: $bg-white;
  border-bottom: 1px solid $border-light;
  
  .tabs-scroll {
    white-space: nowrap;
    padding: 0 16px;
    
    .tab-item {
      display: inline-block;
      padding: 12px 16px;
      font-size: 15px;
      color: $text-secondary;
      position: relative;
      
      &.active {
        color: $primary;
        font-weight: 500;
      }
      
      .tab-indicator {
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 24px;
        height: 3px;
        background-color: $primary;
        border-radius: 3px;
      }
    }
  }
}

// 话题列表滚动区域
.topic-scroll {
  height: calc(100vh - var(--status-bar-height) - 50px - 45px - 56px);
}

// 话题列表
.topic-list {
  padding: 10px 16px;
  
  .topic-item {
    background-color: $bg-white;
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 12px;
    box-shadow: $shadow-light;
    
    // 话题作者信息
    .topic-author {
      display: flex;
      margin-bottom: 12px;
      
      .author-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        object-fit: cover;
        margin-right: 10px;
      }
      
      .author-info {
        flex: 1;
        
        .author-name {
          display: flex;
          align-items: center;
          font-size: 15px;
          font-weight: 500;
          color: $text-primary;
          margin-bottom: 4px;
          
          .verified-badge {
            margin-left: 6px;
          }
        }
        
        .topic-time {
          font-size: 12px;
          color: $text-tertiary;
          
          .topic-category {
            margin-left: 4px;
          }
        }
      }
    }
    
    // 话题内容
    .topic-content {
      margin-bottom: 12px;
      
      .topic-title {
        font-size: 16px;
        font-weight: 600;
        color: $text-primary;
        margin-bottom: 8px;
        line-height: 1.4;
      }
      
      .topic-text {
        font-size: 14px;
        color: $text-secondary;
        line-height: 1.6;
        margin-bottom: 12px;
        
        text {
          display: -webkit-box;
          -webkit-line-clamp: 3;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
      }
      
      // 话题图片
      .topic-images {
        margin-bottom: 12px;
        
        .image-grid {
          display: grid;
          gap: 4px;
          
          &.grid-1 {
            grid-template-columns: 1fr;
          }
          
          &.grid-2 {
            grid-template-columns: repeat(2, 1fr);
          }
          
          &.grid-3 {
            grid-template-columns: repeat(3, 1fr);
          }
        }
        
        .topic-image {
          width: 100%;
          aspect-ratio: 1/1;
          object-fit: cover;
          border-radius: 8px;
        }
        
        .image-count {
          position: absolute;
          bottom: 8px;
          right: 8px;
          background-color: rgba(0, 0, 0, 0.6);
          color: white;
          font-size: 12px;
          padding: 2px 6px;
          border-radius: 4px;
        }
      }
      
      // 话题标签
      .topic-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        
        .tag-item {
          background-color: $bg-light;
          color: $text-secondary;
          font-size: 12px;
          padding: 3px 10px;
          border-radius: 12px;
        }
      }
    }
    
    // 话题互动数据
    .topic-actions {
      display: flex;
      align-items: center;
      padding-top: 8px;
      border-top: 1px solid $border-light;
      
      .action-item {
        display: flex;
        align-items: center;
        margin-right: 24px;
        font-size: 14px;
        color: $text-tertiary;
        
        &:active {
          opacity: 0.7;
        }
        
        .action-count {
          margin-left: 6px;
          
          &.liked {
            color: $danger;
          }
        }
      }
    }
  }
}

// 加载更多
.loading-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px 0;
  color: $text-tertiary;
  
  .loading-text {
    margin-left: 8px;
    font-size: 14px;
  }
}

// 没有更多数据
.no-more {
  text-align: center;
  padding: 20px 0;
  color: $text-tertiary;
  font-size: 14px;
}

// 空状态
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: $text-tertiary;
  
  .empty-text {
    font-size: 16px;
    margin: 20px 0;
  }
  
  .empty-btn {
    background-color: $primary;
    color: white;
    border-radius: 20px;
    padding: 8px 24px;
    font-size: 14px;
  }
}

// 底部导航
.tab-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  background-color: $bg-white;
  border-top: 1px solid $border-light;
  height: 56px;
  
  .tab-bar-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: 10px;
    color: $text-tertiary;
    
    .tab-bar-text {
      margin-top: 4px;
      
      &.active {
        color: $primary;
      }
    }
  }
}
</style>
    